<template>
  <el-dialog
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="上传附件"
    width="800"
    class="dialogStyle"
    @close="handleClose"
  >
    <el-form :model="formParams" label-width="120px" ref="ruleFormRef">
      <el-form-item label="上传附件：">
        <el-upload
          v-model:file-list="formParams.fileList"
          class="upload-demo"
          action="#"
          :before-upload="beforeAvatarUpload"
          :http-request="handleFileChange"
          accept=".rar, .zip, .doc, .docx, .pdf"
          :show-file-list="false"
        >
          <el-button type="default" style="font-size: 14px"
            ><el-icon><UploadFilled /></el-icon>上传文件</el-button
          >
          <template #tip>
            <div class="float-right">
              <div v-for="item in fileList" :key="item.fileId">
                <a
                  :href="item.url"
                  target="_blank"
                  class="text-#409eff ml-10px text-14px"
                  >{{ item.origFileName }}</a
                >
              </div>
            </div>
            <!-- <div class="el-upload__tip float-right" >
              支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过{{
                dialogParam.tableName == 'ord_project.materials'
                  ? '100MB'
                  : '20MB'
              }}且只能上传一份文件
            </div> -->
          </template>
        </el-upload>
        <!-- <div class="text-14px mt-10px" style="width: 100%">
          <div v-for="(item, index) in fileList" :key="item.fileId">
            <a :href="item.url" target="_blank" class="text-#409eff">{{
              item.origFileName
            }}</a>
            <el-button text plain @click="delFileName(index)">删除</el-button>
          </div>
        </div> -->
      </el-form-item>
      <el-form-item label="备注内容:">
        <el-input
          v-model="formParams.cnt"
          type="textarea"
          maxlength="200"
          placeholder="请输入备注内容"
        />
      </el-form-item>
      <div class="footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="btnLoading"
          >保存</el-button
        >
      </div>
    </el-form>
  </el-dialog>
</template>
<script setup name="Appendix">
import { reactive, getCurrentInstance, watchEffect } from 'vue'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import * as Api from '@/api/common/common.js'
const { proxy } = getCurrentInstance()
const props = defineProps({
  // 弹出框是否显示
  dialogParam: {
    required: true
  }
})
const data = reactive({
  dialogVisible: false,
  formParams: {}
})
const { dialogVisible, formParams } = toRefs(data)
const btnLoading = ref(false) //按钮加载状态
watch(
  () => props.dialogParam,
  val => {
    if (JSON.stringify(props.dialogParam) != '{}') {
      init()
    }
  },
  {
    deep: true,
    immediate: true
  }
)
async function init() {
  dialogVisible.value = props.dialogParam.isVisible
}
/*** 文件上传 start */
let fileList = ref([])
/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  if (props.dialogParam.tableName == 'ord_project.materials') {
    if (rawFile.size / 1024 / 1024 > 100) {
      proxy.$modal.msgError('单个文件不能超过100MB!')
      return false
    }
  } else {
    if (rawFile.size / 1024 / 1024 > 20) {
      proxy.$modal.msgError('单个文件不能超过20MB!')
      return false
    }
  }
}
// 上传合同
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value[0] = res.data
    }
  } catch (error) {
    // proxy.$modal.msgError(error)
  }
}
// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
/*****文件上传 end */
const onSubmit = async () => {
  if (fileList.value.length == 0) {
    proxy.$modal.msgError('附件必须上传')
    return false
  }
  let params = { ...fileList.value[0] }
  params.remark = formParams.value.cnt
  params.businessId = props.dialogParam.businessId
  params.tableName = props.dialogParam.tableName
  btnLoading.value = true
  try {
    const res = await Api.updateFile(params)
    if (res.code === 200) {
      proxy.$modal.msgSuccess('操作成功')
      btnLoading.value = false
      handleClose()
    }
  } catch (error) {
    btnLoading.value = false
  }
}
const emit = defineEmits(['close', 'xm-appendix'])
// 取消
function handleClose() {
  dialogVisible.value = false
  btnLoading.value = false
  formParams.value = {}
  fileList.value = []
  //特殊详情 -项目所需材料
  if (props.dialogParam.tableName == 'ord_project.materials') {
    emit('close', 'xm-appendix')
  } else {
    emit('close', 'appendix')
  }
}
</script>
<style lang="scss">
.dialogStyle {
  .el-dialog__header {
    @apply mr-0  text-#666 font-semibold bg-#f5f5f5;
  }
  .footer {
    @apply text-right border-t border-t-solid border-gray-100 pt-20px mt-20px;
  }
}
</style>
